package com.ykt.weixin;

import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.StrKit;
import com.ykt.common.pay.wx.WxPayResult;
import com.ykt.model.Order;
import com.ykt.model.PayRecord;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信支付回调
 *
 * @author wing
 * @version 1.0.0
 */
@ControllerBind(controllerKey="/weixin")
public class WeixinController extends Controller {

	private final  static Logger log = LoggerFactory.getLogger(WeixinController.class);
    
    public void wxNotify(){
    	HttpServletRequest request = this.getRequest();
		HttpServletResponse response = this.getResponse();
		
		log.info("==========================微信支付回调数据开始====================");
		//示例报文
//		String xml = "<xml><appid><![CDATA[wxb4dc385f953b356e]]></appid><bank_type><![CDATA[CCB_CREDIT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1228442802]]></mch_id><nonce_str><![CDATA[1002477130]]></nonce_str><openid><![CDATA[o-HREuJzRr3moMvv990VdfnQ8x4k]]></openid><out_trade_no><![CDATA[1000000000051249]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[1269E03E43F2B8C388A414EDAE185CEE]]></sign><time_end><![CDATA[20150324100405]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[1009530574201503240036299496]]></transaction_id></xml>";
		String inputLine;
		String notityXml = "";
		String resXml = "";

		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		log.info("接收到的报文：" + notityXml);
		BufferedOutputStream out = null;
		try{
			if(StrKit.notBlank(notityXml)){
				Map m = parseXmlToList(notityXml);

				WxPayResult wpr = new WxPayResult();
				wpr.setAppid(m.get("appid").toString());
				wpr.setBankType(m.get("bank_type").toString());
				wpr.setCashFee(m.get("cash_fee").toString());
				wpr.setFeeType(m.get("fee_type").toString());
				wpr.setIsSubscribe(m.get("is_subscribe").toString());
				wpr.setMchId(m.get("mch_id").toString());
				wpr.setNonceStr(m.get("nonce_str").toString());
				wpr.setOpenid(m.get("openid").toString());
				wpr.setOutTradeNo(m.get("out_trade_no").toString());
				wpr.setResultCode(m.get("result_code").toString());
				wpr.setReturnCode(m.get("return_code").toString());
				wpr.setSign(m.get("sign").toString());
				wpr.setTimeEnd(m.get("time_end").toString());
				wpr.setTotalFee(m.get("total_fee").toString());
				wpr.setTradeType(m.get("trade_type").toString());
				wpr.setTransactionId(m.get("transaction_id").toString());

				if("SUCCESS".equals(wpr.getResultCode())){
					//支付成功
					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

				}else{
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
				}
				log.info("resXml======="+resXml);

				//String payNo = m.get("out_trade_no").toString();
				//log.info("payNo======="+payNo);
				String orderNo = m.get("out_trade_no").toString();
				log.info("orderNo======="+orderNo);
				
				String wxPayId = m.get("transaction_id").toString();
				try{
					Date nowDate = new Date();

					if("SUCCESS".equals(wpr.getResultCode())){
						//do 支付成功之后的操作
						log.info("========支付成功=======");
//						List<PayRecord> prList = PayRecord.dao.find("select * from pay_record where pay_no=?", payNo);
//						for(PayRecord pr : prList){
//							pr.set("status", "SUCCESS");
//							pr.set("serial_no", wxPayId);
//							pr.set("pay_time", nowDate);
//							pr.update();
//							
//							Order o = Order.dao.findById(pr.getInt("order_id"));
//							o.set("status", "MERCHANT_UNDELIVERY");
//							o.set("pay_time", nowDate);
//							o.set("updated_time", nowDate);
//							//o.update();
//							boolean flag = o.update();
//					        if(flag){
//					        	List<Order> orderList = Order.dao.findByOrderPno(o.getStr(Order.orderNo));
//					        	for(Order item : orderList){
//					        		item.set("status", "MERCHANT_UNDELIVERY");
//					        		item.set("pay_time", nowDate);
//					        		item.set("updated_time", nowDate);
//					        		item.update();
//					        	}
//					        }
//						}
						
						/***************以订单的order_no直接传给微信的处理********************/
						Order item = Order.dao.findFirst("select * from `order` where order_no=?", orderNo);
						item.set("status", "MERCHANT_UNDELIVERY");
						item.set("pay_time", nowDate);
						item.set("updated_time", nowDate);
						boolean flag = item.update();
						if(flag){
							List<Order> orderList = Order.dao.findByOrderPno(item.getStr(Order.order_no));
				        	for(Order o : orderList){
				        		o.set("status", "MERCHANT_UNDELIVERY");
				        		o.set("pay_time", nowDate);
				        		o.set("updated_time", nowDate);
				        		o.update();
				        	}
						}
						PayRecord pr = PayRecord.dao.findFirst("select * from pay_record where order_id=? order by id desc", item.getId());
						pr.set("status", "SUCCESS");
						pr.set("serial_no", wxPayId);
						pr.set("pay_time", nowDate);
						pr.update();
							
						/***************以订单的order_no直接传给微信的处理end********************/
					}else{
						log.info("========支付失败=======");
//						List<PayRecord> prList = PayRecord.dao.find("select * from pay_record where pay_no=?", payNo);
//						for(PayRecord pr : prList){
//							pr.set("status", "FAIL");
//							pr.set("serial_no", wxPayId);
//							pr.set("pay_time", nowDate);
//							pr.update();
//						}
						/***************以订单的order_no直接传给微信的处理********************/
						Order item = Order.dao.findFirst("select * from `order` where order_no=?", orderNo);
						PayRecord pr = PayRecord.dao.findFirst("select * from pay_record where order_id=? order by id desc", item.getId());
						pr.set("status", "FAIL");
						pr.set("serial_no", wxPayId);
						pr.set("pay_time", nowDate);
						pr.update();
						/***************以订单的order_no直接传给微信的处理end********************/
					}
				}catch (Exception e) {
					e.printStackTrace();
				}

				log.info("==========================微信支付回调数据结束====================");

				out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(out!=null){
				try {
					out.flush();
					out.close();	
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    	
		renderNull();
    }
    
	private static Map parseXmlToList(String xml) {
		Map retMap = new HashMap();
		try {
			StringReader read = new StringReader(xml);
			// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			// 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			// 通过输入源构造一个Document
			Document doc = (Document) sb.build(source);
			Element root = doc.getRootElement();// 指向根节点
			List<Element> es = root.getChildren();
			if (es != null && es.size() != 0) {
				for (Element element : es) {
					retMap.put(element.getName(), element.getValue());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;
	}
}
